package com.zgl.gemduel.controller;

import com.zgl.gemduel.model.RoomResource;
import com.zgl.gemduel.service.RoomResourceService;
import com.zgl.gemduel.service.WebSocketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.stereotype.Controller;

import java.util.Map;

@Controller
public class WebSocketController {

    @Autowired
    private WebSocketService webSocketService;

    @Autowired
    private RoomResourceService roomResourceService;

    /**
     * 处理客户端加入房间的请求
     * @param roomId 房间ID
     * @param headerAccessor 消息头访问器
     */
    @MessageMapping("/join_room")
    public void joinRoom(@Payload Map<String, String> roomId, SimpMessageHeaderAccessor headerAccessor) {
        String sessionId = headerAccessor.getSessionId();
        String room = roomId.get("roomId");
        
        if (sessionId != null && room != null) {
            webSocketService.joinRoom(sessionId, room);
            
            // 发送加入房间成功的消息给客户端
            RoomResource roomResource = roomResourceService.getRoomResource(room);
            if (roomResource != null) {
                webSocketService.syncRoomResource(sessionId, roomResource);
            }
        }
    }

    /**
     * 处理客户端发送的游戏指令
     * @param command 指令数据
     */
    @MessageMapping("/game_command")
    public void handleGameCommand(@Payload Map<String, Object> command) {
        String roomId = (String) command.get("roomId");
        
        if (roomId != null) {
            webSocketService.handleGameCommand(roomId, command);
        }
    }

    /**
     * 处理客户端离开房间的请求
     * @param headerAccessor 消息头访问器
     */
    @MessageMapping("/leave_room")
    public void leaveRoom(SimpMessageHeaderAccessor headerAccessor) {
        String sessionId = headerAccessor.getSessionId();
        
        if (sessionId != null) {
            webSocketService.leaveRoom(sessionId);
        }
    }
}